home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / first4th.zip / CHAP01.TXT < prev    next >
Text File  |  1992-11-01  |  26KB  |  526 lines

  1.     Programming for the Utter Beginner Who has an MS-DOS Computer
  2.                 Copyright (c) 1991,1992 by Michael Ham
  3.  
  4.                             Table of Contents
  5.     Introduction
  6.             1. How to Read This Book
  7.  
  8.     Part I:  First steps
  9.             2. Your First Program
  10.             3. Polishing the Program
  11.             4. Saving Your Program
  12.  
  13.     Part II:  Controlling the screen and basic structures
  14.             5. A Title Screen and Other Display Magic
  15.             6. Loops Within Loops:  An Example
  16.  
  17.     Part III:  Building a menu (and learning a lot)
  18.             7. Moving Toward a Menu
  19.             8. Characters from the Keyboard
  20.             9. Making a Choice
  21.            10. Return to Loops
  22.            11. Closer to the Menu
  23.            12. Making the Menu At Last
  24.  
  25.     Part IV:  Your own database of mailing addresses
  26.            13. The Printer and the Disk
  27.            14. Collecting Strings
  28.            15. Building the Record: the Plan
  29.            16. Building the Record: the Program
  30.            17. Making a Real Live Program
  31.  
  32.     Part V:  Some useful tools
  33.            18. Out of Sorts?  Here's One You'll Like
  34.            19. Double the Precision, Double the Fun
  35.            20. Converting Numbers into Strings
  36.            21. Double-Precision at Work
  37.            22. Collecting Numbers from the Keyboard
  38.  
  39.     Part VI:  Harnessing the powers of DOS
  40.            23. DOS Filenames:  Correction versus Prevention
  41.            24. DOS and Forth
  42.            25. From BLOCK to File
  43.  
  44.     Part VII:  The special powers of Forth
  45.            26. Inside Forth
  46.            27. Defining Words
  47.  
  48.     Part VIII:  Floating point, graphics, and final remarks
  49.            28. Just When You Thought You Were Safe from Numbers
  50.            29. Return to the Screen
  51.            30. Remarks on Design
  52.  
  53.     Bibliography and List of Organizations
  54.                               Introduction
  55.  
  56.          This book teaches you how to write programs for your IBM
  57.     PC-compatible computer.  You don't need to know anything about
  58.     programming or computers:  the book either teaches you what you
  59.     need to know or tells you where to find it (for example, in your
  60.     DOS manual).
  61.  
  62.         Why would anyone want to learn programming?  Several reasons:
  63.  
  64.         Control:  Our world increasingly depends on--and is
  65.     controlled by--technology, which finds its fullest expression and
  66.     most useful tool in the computer.  Some people feel a loss of
  67.     control, a sense that somewhere a computer is using a flawed
  68.     program to make decisions about their lives.  The popularity of
  69.     stories about erroneous computer-prepared bills attests to our
  70.     fears.  When you learn to program, you learn how to control a
  71.     computer, a role reversal simultaneously satisfying and healthy.
  72.  
  73.         Apart from technology--perhaps *especially* apart from
  74.     technology--the world works according to rules unstated and
  75.     ambiguous.  Games and sports are popular in part because they
  76.     provide a microcosm of endeavor defined by explicit and
  77.     unambiguous rules, allowing players for a while the comfort of
  78.     having a specified goal and knowing the precise means (and
  79.     limitations) available for achieving the goal.  Programming's
  80.     microcosm also is based on clear rules, but the computer provides
  81.     an open-ended environment in which you set the goal and can in
  82.     fact go beyond a game to create useful things.
  83.  
  84.         Craft:  Programming thus gives you the satisfactions of a
  85.     craft.  Your work produces artifacts that embody your ideas,
  86.     though since the artifacts are made of symbols and not materials,
  87.     programming is more akin to writing than to woodworking.  As you
  88.     work, you search for the right words, the balanced phrase, the
  89.     logical progression (all in accordance with the rules) to attain
  90.     the goal you have in mind.  With one, you make a sonnet; with the
  91.     other, a program.
  92.  
  93.         Beauty:  Programming provides also the pleasures of an
  94.     aesthetic experience.  When you find the minimal set of words
  95.     (actions) that produces a desired effect, you enjoy a profound
  96.     satisfaction, a pride in your work, that is the recognition of
  97.     the rightness of the approach.  When you watch in operation the
  98.     final version of your program--well-crafted to its purpose--you
  99.     delight in the movements of a complex (though abstract)
  100.     mechanism, all its myriad parts interacting appropriately.  You
  101.     have created a kind of abstract kinetic sculpture that follows
  102.     your instructions to fulfill your objective.
  103.  
  104.         Practicality:  Since your objective in programming is
  105.     typically some practical purpose, we find a final answer to the
  106.     question of why learn programming:  the practical answer.  Some
  107.     people make their living as programmers; others need a particular
  108.     program to support their work or hobby and find nothing on the
  109.     market that exactly meets their need.  Programming offers them
  110.     the means to reach practical goals.
  111.  
  112.         You can't learn programming without learning a programming
  113.     language.  The programming language used in this book is Forth.
  114.     Why did I choose Forth?
  115.  
  116.         The particular programming language clearly doesn't make any
  117.     difference to the person who USES the program--she or he doesn't
  118.     care whether the program was written in Assembler, FORTRAN,
  119.     COBOL, ALGOL, PL/1, RPG, APL, LISP, PROLOG, LOGO, SNOBOL, JOVIAL,
  120.     Pascal, Ada, Modula-2, Actor, SAIL, STOIC, BASIC, BASICA, QUICK-
  121.     BASIC, TRUE BASIC, Visual BASIC, or B, or C, or C++.  The user
  122.     really doesn't care whether the work is done by a program or by a
  123.     team of tiny trained bees inside the computer case.
  124.  
  125.         So user preference is no help in determining the language to
  126.     use.  And as you see, many languages are available, each with
  127.     its special characteristics, mission, and proponents.  Forth
  128.     certainly is not heavily promoted:  no major hardware or
  129.     software company proclaims it as the latest language, the one
  130.     that at last will prevent errors, improve productivity, and fight
  131.     tooth decay.  Forth isn't taught in high schools or colleges as
  132.     the ideal "introductory" language.  It hasn't the imprimatur of
  133.     science, though it saw first light in scientific applications for
  134.     instrument control and data acquisition and analysis.
  135.  
  136.         Yet Forth continues to be widely used.  As computers shrink
  137.     to take up residence inside our automobiles, appliances, and
  138.     toys, Forth is frequently picked for the programs embedded in
  139.     these machines.  And some software sold commercially is written
  140.     in Forth.
  141.  
  142.         Forth is not packaged with new computers; instead, as each
  143.     new processor is released, Forth is promptly ported to it,
  144.     generally by the volunteered labor of some programmer eager to
  145.     try out the new computer.  Forth is used because it is easy to
  146.     develop, well within the reach of the average programmer, and the
  147.     resulting language is powerful, fast, and compact.  Forth is the
  148.     people's movement in computing, the unruly outsider that can't be
  149.     left behind because it is simply too useful, too good, too
  150.     powerful, too easy--and so the programmers bring it.  For
  151.     themselves.
  152.  
  153.         I wanted to use a good programming language for this book,
  154.     so I took the language that programmers created for themselves
  155.     and that they determinedly carry with them as they move from
  156.     machine to machine.  That language is Forth.
  157.  
  158.         Forth proves to be an excellent choice for a beginning
  159.     programmer for various reasons, the primary one being that Forth
  160.     offers fewer impediments than most programming languages.
  161.     Because practicing programmers developed and refined Forth in the
  162.     field (as it were), its design was shaped by experience and it
  163.     has evolved into a powerful programming tool.
  164.  
  165.         *   Forth allows you to develop programs incrementally,
  166.             through a series of short routines that can be run by
  167.             themselves.  By writing the program piecemeal, you avoid
  168.             having to tackle the whole thing at once.  By keeping
  169.             each piece small, you can completely understand it.  This
  170.             procedure is not only easier, it results in fewer program
  171.             errors ("bugs").
  172.  
  173.         *   Forth is fast; in particular, it is much faster than
  174.             interpreted BASIC, a language commonly used by beginners.
  175.  
  176.         *   Forth is fully interactive, which means that as soon as
  177.             you write a part of your program, you can run it and test
  178.             it.  This allows you to revise and refine the program on
  179.             the spot, as you go.
  180.  
  181.         *   Forth allows you to build on your own experience.  You
  182.             can extend it to include new commands and data structures
  183.             and objects that you create to address the kind of
  184.             programming problems you most often encounter.
  185.  
  186.         *   Forth can be used to produce programs that you can save
  187.             on disk and that run by themselves.
  188.  
  189.          The Forth supplied with this book is FIRST/FORTH, based on
  190.     (and derived from) a professional product, UR/FORTH, published by
  191.     Laboratory Microsystems, Inc. (LMI) of Los Angeles, California.
  192.     LMI is a leading Forth vendor, with a long history and excellent
  193.     products, which now include WinForth for Microsoft Windows.
  194.     LMI's Forth conforms to the most recent Forth standard, the 83
  195.     Standard. Although FIRST/FORTH does not include all the features
  196.     of UR/FORTH, it includes the essentials; what you learn here will
  197.     enable you to write real programs, and your programs will run
  198.     equally well (and somewhat faster) in UR/FORTH.
  199.  
  200.          FIRST/FORTH, specifically tailored for the beginning
  201.     programmer, does not include source code for the editor, the
  202.     electives, and the binary overlays. It lacks the assembly
  203.     language package, the special memory management commands, and the
  204.     hardware floating point instruction sets.  All of these are
  205.     included with LMI's professional Forths.
  206.  
  207.          As with all LMI products, you can sell or share the
  208.     programs you write without paying any royalties or license fees,
  209.     provided that you distribute only program files created by the
  210.     TURNKEY command described in this book.  You can, of course,
  211.     distribute your source code files with no restrictions.
  212.  
  213.          By the end of this book you will have written a respectable
  214.     program.  You will be familiar with the Forth language and its
  215.     conventions, and (more important) you will also understand the
  216.     nature of the programming activity and the issues that it must
  217.     address.  The goal of the book is not to teach a programming
  218.     language, but to teach programming--the language is but the means
  219.     to the end.
  220.  
  221.  
  222.                               Chapter 1
  223.  
  224.                           How to Use This Book
  225.  
  226.  
  227.          This book will teach you how to design, write, and debug
  228.     simple programs.  You'll learn programming commands and program
  229.     development as you write programs.  The emphasis is on
  230.     programming, not on the programming language.  Some of the
  231.     programs are simple exercises; some are basic tools or structures
  232.     you can extend and use in your own programs.  To get the most out
  233.     of this book, heed a few basic rules:
  234.  
  235.     1.  Read the book with a pen or highlighter in your hand.
  236.  
  237.          Underline or circle new terms.  Write questions and notes in
  238.     the margin.  Record discoveries you have made.  Make your own
  239.     index in the back of the book, noting terms and ideas important
  240.     to you and the pages on which they are discussed.  Restate
  241.     explanations in your own terms.  Draw diagrams to make concepts
  242.     and relationships clearer.  Make this your book.
  243.  
  244.     2.  Read the book at the computer and do each example.
  245.  
  246.          Have Forth loaded  and enter the examples as you read them.
  247.     Doing the examples teaches a part of you that reading the
  248.     examples doesn't reach--and that's the part of you that writes
  249.     programs.  Of course, you should also do the exercises in the
  250.     book, but do the examples as well.
  251.  
  252.     3.  Experiment.
  253.  
  254.          If some point is unclear or you wonder what would happen to
  255.     an example under different circumstances, TRY IT OUT.  Sometimes
  256.     what you try will work the way you expect, sometimes not.  The
  257.     worst that can happen is that:
  258.  
  259.          *  you don't get the result you want; or
  260.  
  261.          *  you get an information message on why it won't work; or
  262.  
  263.          *  you suddenly find yourself back in the operating system
  264.             (DOS), with the A> (or C>) prompt; or
  265.  
  266.          *  the computer gets the blind staggers:  the screen shows
  267.             only a flickering display of random garbage and nothing
  268.             happens when you press the keys; or
  269.  
  270.          *  the computer goes into a catatonic trance and does
  271.             nothing, and nothing happens when you press the keys.
  272.  
  273.          Yes, the computer will occasionally sulk and become totally
  274.     unresponsive as the result of an experiment.  This corresponds to
  275.     what happens when you learn tennis:  you knock the ball over the
  276.     fence, and then must run after it.  But because you're using a
  277.     computer, recovery is much easier:
  278.  
  279.           a.  First, try pressing Ctrl-Break.  Then press the return
  280.               key a few times to see if the "ok" comes back.
  281.  
  282.           b.  If that doesn't work, try pressing Ctrl-Alt-Del to
  283.               reboot the system (that is, reload the operating system
  284.               and start over).  You then can return to Forth and try
  285.               some other approach.
  286.  
  287.           c.  If that doesn't work, turn off the computer, wait a few
  288.               seconds, and turn it back on.  This complete
  289.               resurrection will always work (unless your program has
  290.               gone so far awry that it has written over the system
  291.               files).
  292.  
  293.          You don't have to fear a system crash.  It's a normal part
  294.     of learning; beginning musicians hit wrong notes, beginning
  295.     tennis players hit the ball over the fence, and beginning (and
  296.     even experienced!) programmers occasionally crash the system.
  297.  
  298.     4.  Look at the answers.
  299.  
  300.          When you learn how to read the file ANSWERS.SCR, compare
  301.     your answers to the exercises to the answers in the file.  If
  302.     your answers are different, determine both the cause and the
  303.     effect of the difference--"different" doesn't necessarily mean
  304.     "wrong."  Experiment with variations, seek improvements.  But
  305.     always attempt to work out the answer yourself before you look.
  306.  
  307.     5.  Don't jump ahead
  308.  
  309.          Some readers have a habit of jumping ahead several chapters
  310.     and reading around.  In a book such as this, where you are
  311.     learning new terms and new techniques on almost every page,
  312.     jumping ahead shows you gobbledygook, which can be discouraging.
  313.     If you work your way through the book, one page at a time, you
  314.     will understand the later material when you get to it.
  315.  
  316.          This is not to say that you should stay stuck on some
  317.     particular word on concept.  If you have worked your way up to
  318.     some point in the book and feel stuck, flow around that
  319.     difficulty and keeping going.  Later material often illuminates
  320.     earlier difficulties.  But avoid simply leaping ahead without
  321.     working through the intervening material.
  322.  
  323.     6.  Speak up.
  324.  
  325.          If you don't understand some example or you find some
  326.     section confusing, let me know.  I am happy to help you, and your
  327.     questions and comments will help me improve this book.
  328.  
  329.          You can write to me in care of Laboratory Microsystems, Inc.
  330.     (12555 West Jefferson Boulevard, Suite 202, Los Angeles, CA
  331.     90066), or leave a message to MICHAEL HAM on the LMI bulletin
  332.     board system (213/365-3530; 1200/2400/9600 bps; 8 bits, no
  333.     parity), or send an email message to   mham   on BIX.
  334.  
  335.     Up the slippery learning curve
  336.  
  337.          Those who begin to learn something completely new often
  338.     experience a strange phenomenon that I call "Teflon memory."
  339.  
  340.          Each new fact that enters the mind slides away as soon as
  341.     the mind turns to a new thought.  The most elementary facts must
  342.     be learned and relearned repeatedly before one finally sticks
  343.     and is available for recall.
  344.  
  345.          As soon as one fact is retained, it offers a toehold for the
  346.     next.  The two link to catch a third, and soon the facts you
  347.     have accumulated form a net that readily captures new facts
  348.     about the topic from your reading and experience.  By this time
  349.     you are puzzled that you didn't grasp instantly such simple and
  350.     self-evident things as those early facts.
  351.  
  352.          The strange awkwardness of the early stages of learning
  353.     something new would be familiar if we routinely and habitually
  354.     ventured into totally new territory.  Naturally enough, however,
  355.     we seldom take up something completely new; the familiar not only
  356.     is comfortable, it allows us to enjoy the skills already
  357.     developed from our earlier experience.
  358.  
  359.          Experienced card players, for example, generally prefer to
  360.     learn a new card game (which they can learn quickly by relating
  361.     it to card games they already know) than a completely different
  362.     kind of game.  Those who try to learn bridge without any
  363.     previous experience with cards find facts sliding away on the
  364.     Teflon memory of the novice.  Only with patience and persistence
  365.     do they see the first fragments of knowledge stay long enough to
  366.     begin building the structure of learning.  Unless our commitment
  367.     to the goal is strong enough to keep us involved, we retreat to
  368.     the familiar and abandon the awkwardness of the new.
  369.  
  370.          Because we generally stick to the territory we already know,
  371.     the feelings that arise in the initial stages of new learning
  372.     are strange and uncomfortable.  We want a royal road to
  373.     knowledge, a road that takes us quickly from the discomfort of
  374.     our ignorance and uncertainty into the power and security of
  375.     mastery.
  376.  
  377.          And a royal road exists.  To find an efficient way to learn,
  378.     look to efficient learners.  The most efficient learners are
  379.     small children:  they have the most to learn, and they learn the
  380.     quickest.  How do they do it?
  381.  
  382.          They wrap themselves around their experience and
  383.     observe everything that happens without being blinded by
  384.     expectations.  They multiply the number of experiences by taking
  385.     everything within their grasp and playing vigorously with it in
  386.     every way.  They don't fear mistakes because mistakes are not
  387.     possible:  everything that happens is
  388.     information, grist for the mill of their curiosity.
  389.  
  390.          The toddler who tries to eat a block finds a fact, not a
  391.     failure:  this particular block seems inedible.  The toddler who
  392.     throws a glass to the floor discovers that glass shatters and
  393.     makes an interesting sound, a lesson to be verified immediately
  394.     if another glass is within reach.
  395.  
  396.          Experience is not one big thing, it is a thousand little
  397.     things.  That is why it takes so long to acquire:  like panning
  398.     for gold, tiny grains are added to the hoard one by one, and as
  399.     the grains accumulate, the value grows.
  400.  
  401.          The best route to mastery is to exploit experience:  work
  402.     with every word and idea, push them this way and that.  Observe
  403.     whatever happens.  When you think you've found a pattern, test
  404.     it.  In a word, play with the computer and the commands.  See
  405.     what they do.  Become a programming toddler, and delight in the
  406.     sense of discovery.  And in the early stages, when facts slide
  407.     quickly from memory, go back and reread the manual when you have
  408.     to--everyone does.
  409.  
  410.     The Road Ahead
  411.  
  412.          This book winds its way through various experiences.  You
  413.     learn commands by using them, playing with them, and making them
  414.     move, not by memorizing them.  Many commands are used in the
  415.     programming examples, others you can play with on your own.  Be
  416.     patient with yourself, be inquisitive, enjoy the process, and
  417.     before the end of the book you will be programming.
  418.  
  419.          The early examples in the book are simple because you don't
  420.     yet have the commands and concepts for complex examples.
  421.     Chapters 2 and 3 work on a simple program to display a single
  422.     phrase on the screen.  In chapter 4 you are introduced to the
  423.     editor, which allows you to save your programs to disk.  With
  424.     this capability, you can begin to build more complex programs.
  425.  
  426.          Chapters 5 and 6 complete the early work of screen display,
  427.     teaching you along the way about an important programming
  428.     technique, the loop.
  429.  
  430.          Chapters 7 through 12 have as their overall goal the
  431.     development of an on-screen menu from which the user of a program
  432.     can select the options he or she wants.  The menu is a basic
  433.     element in many programs, and to construct it you learn a wide
  434.     range of essential computer information:  how to make sounds,
  435.     collect input from the keyboard, make choices, and so on.
  436.  
  437.          The next step after making a menu is to develop a program to
  438.     put behind it.  I use an address book program:  you develop a
  439.     program that allows you to create a database of mailing addresses
  440.     and print them as needed.  This enterprise takes five chapters,
  441.     13 through 17, and through the rest of the book we periodically
  442.     revisit this program to augment or refine it.
  443.  
  444.          Chapter 18 shows you how to sort data.  Chapters 19 and 20
  445.     show you how to use larger numbers and how to display numbers in
  446.     various formats (with commas, decimal points, dashes, and the
  447.     like).  Chapters 21 and 22 use these larger numbers to show you
  448.     some useful techniques for application programs, including a
  449.     general-purpose word that collects numeric data.
  450.  
  451.          DOS provides you, as a programmer, with some powerful
  452.     tools. These are discussed in chapters 23 through 25.  The
  453.     address book program is revisited to put these new capabilities
  454.     to work.
  455.  
  456.          Chapters 26 and 27 show you Forth's special powers and how
  457.     to use those powers in your programs.  In particular, Forth's
  458.     ability to let you define entirely new data structures is
  459.     explained with examples.
  460.  
  461.          Chapter 28 introduces the floating-point operations and
  462.     shows their use and limitations, and chapter 29 takes you into
  463.     the world of graphic displays.
  464.  
  465.          Chapter 30 ends the book with a collection of general
  466.     principles and rules of thumb for applications programming.
  467.                         REGISTRATION OF FIRST/FORTH
  468.  
  469.     Complete this form and mail it with payment (see below) to:
  470.  
  471.          FIRST/FORTH Registration
  472.          Laboratory Microsystems, Inc.
  473.          12555 West Jefferson Boulevard  Suite 202
  474.          Los Angeles, CA 90066
  475.          FAX 310/301-0761
  476.  
  477.     When your payment is received, you will be shipped a copy of
  478.     *Programming for the Utter Beginner*.  Your registration will be
  479.     recorded so that you will receive information on any upgrades to
  480.     FIRST/FORTH and on other LMI products. In addition, you will
  481.     receive a credit of $20 toward the purchase of UR/FORTH or WinForth.
  482.  
  483.     UR/FORTH is a professional development system for DOS. It includes
  484.          graphics, hardware and software floating point, DOS extensions,
  485.          and full documentation. It is available in 16-bit and 32-bit
  486.          versions.  FIRST/FORTH source code will run directly in UR/FORTH.
  487.  
  488.     WinForth is a complete professional Forth development system for
  489.          the Microsoft Windows environment.
  490.  
  491.     Please print.  California residents:  Please include sales tax.
  492.  
  493.     Name:    _______________________________________________________
  494.  
  495.     Address: _______________________________________________________
  496.  
  497.              _______________________________________________________
  498.  
  499.     City:    ___________________________ State: ______  ZIP: _______
  500.  
  501.     Daytime telephone: (_______) ___________________
  502.  
  503.     If you wish to buy additional copies of *Programming for the
  504.     Utter Beginner* (each with a diskette containing FIRST/FORTH and
  505.     all associated files), please indicate below:
  506.  
  507.       Registration fee for software        =  $ 49.95
  508.       Additional copies: ____ x $54.95     = _________
  509.  
  510.       Subtotal                             = _________
  511.       California residents: sales tax      = _________
  512.       Shipping/handling registration copy  =     5.00
  513.       Shipping/handling addln copies @ $5  = _________
  514.       Total                                = _________
  515.  
  516.       For additional copies, indicate diskette size:
  517.                                      [] 3.5"   [] 5.25"
  518.  
  519.       Indicate method of payment:    [] check  [] money order
  520.                                      [] VISA*  [] MasterCard*
  521.  
  522.       *Card number: ____________________________  Exp date:________
  523.  
  524.        Signature:  _____________________________  Date: ___________
  525.  
  526.